package app.models.booking;

import app.Const;
import app.models.member.Member;
import app.models.sys.MerchantBrand;
import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.kit.common.RandomStringKit;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author liuhui
 * @version 1.0 14-5-24 下午8:02
 */
@TableBind(tableName = "ol_booking_ktv")
public class KtvBooking extends Model<KtvBooking> {

    public static final  KtvBooking dao              = new KtvBooking();
    private static final Logger     logger           = LoggerFactory.getLogger(KtvProject.class);
    private static final long       serialVersionUID = -9024698439776757458L;

    public Page<KtvBooking> datatable(DatatablesCriterias criterias, String captcha, String phone, String starttime, String endtime) {
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");

        StringBuilder sb = new StringBuilder(" WHERE 1=1 ");
        List<Object> param = Lists.newArrayList();

        if (!Strings.isNullOrEmpty(captcha)) {
            sb.append(" AND captcha like ?");
            param.add("%"+captcha+"%");
        }
        if (!Strings.isNullOrEmpty(phone)) {
            sb.append(" AND phone like ? ");
            param.add("%"+phone+"%");
        }

        if (!Strings.isNullOrEmpty(starttime)) {
            sb.append(" AND booking_date >= ?");
            param.add(starttime);
        }
        if (!Strings.isNullOrEmpty(endtime)) {
            sb.append(" AND booking_date <= ?");
            param.add(endtime);
        }

        int pageSize = criterias.getDisplaySize();
        int start = criterias.getDisplayStart() / pageSize + 1;
        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();

        String where = SqlKit.sql("ktvbooking.columns-where") + sb.toString();

        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            final String byColumns = orderBy.toString();
            if (!Strings.isNullOrEmpty(byColumns)) {
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY booking_date DESC";
        }

        logger.debug(SqlKit.sql("ktvbooking.columns-select") + where);
        if(param.size() > 0 ){
            return paginate(start, pageSize, SqlKit.sql("ktvbooking.columns-select"), where,param.toArray());
        }else {
            return paginate(start, pageSize, SqlKit.sql("ktvbooking.columns-select"), where);
        }
    }


    public Page<KtvBooking> findByDateAndCodeAndPhone(String start, String end, String code, String phone, int page) {

        String where = SqlKit.sql("ktvbooking.columns-where") + " WHERE booking_date BETWEEN ? AND ? ";
        List<Object> params = Lists.newArrayListWithCapacity(3);
        params.add(start);
        params.add(end);
        if (!Strings.isNullOrEmpty(phone)) {
            where += " AND phone =? ";
            params.add(phone);
        }
        if (!Strings.isNullOrEmpty(code)) {

            where += " AND captcha =? ";
            params.add(code);
        }
        int pageNumber = 15;
        return paginate(((page - 1) * pageNumber) + 1, pageNumber, SqlKit.sql("ktvbooking.findByDateAndCodeAndPhone"), where, params.toArray());
    }

    public long countByProject(long project) {
        Number number = Db.queryNumber(SqlKit.sql("ktvbooking.countByProject"), project);
        return number != null ? number.longValue() : 0l;
    }

    public int getBookingCountByMid(long mid) {
        Number number = Db.queryNumber(SqlKit.sql("ktvbooking.getBookingCountByMid"), mid);
        return number.intValue();
    }

    public List<KtvBooking> findByStusAndMid(int status, long mid) {
        return find(SqlKit.sql("ktvbooking.findByStusAndMid"), status, mid);
    }

    public List<KtvBooking> findBookingListByMid(long mid) {
        return find(SqlKit.sql("ktvbooking.findBookingListByMid"),mid);
    }

    public boolean booking(KtvProject ktvProject, String name, String phone, Member member) {
        final DateTime nowTime = DateTime.now();
        Date now = nowTime.toDate();
        try {
            MerchantBrand mb = MerchantBrand.dao.findByBrand(ktvProject.getLong("brand"));

            final int project_id = ktvProject.getNumber(AppFunc.TABLE_PK_COLUMN).intValue();
            // 生成随机码
            String captcha = RandomStringKit.randomNumeric(6);
            final KtvBooking ktvBooking = new KtvBooking();
            ktvBooking.set("name", name);
            ktvBooking.set("phone", phone);
            ktvBooking.set("member", member.getNumber(AppFunc.TABLE_PK_COLUMN).longValue());
            ktvBooking.set("project", project_id);
            ktvBooking.set("project_name", ktvProject.get("name"));
            ktvBooking.set("create_time", now);
            ktvBooking.set("booking_date", now);
            ktvBooking.set("captcha", captcha);
            if (mb != null) {
                ktvBooking.set("merchant", mb.get("merchant"));
            }
            ktvBooking.set("status", Const.BOOKING_STATUS.STATUS_1);
            ktvBooking.save();

            KtvStat stat = KtvStat.dao.findByDay(nowTime);
            final int booking_id = ktvBooking.getNumber(AppFunc.TABLE_PK_COLUMN).intValue();
            if (stat == null) {
                stat = new KtvStat();
                stat.set("stat_date", now);
                stat.set("numbers", 1);
                stat.set("booking_ids", booking_id);
                stat.set("project_ids", project_id);
                stat.save();
            } else {
                stat.set("numbers", stat.getNumber("numbers").intValue() + 1);
                stat.set("booking_ids", stat.getStr("booking_ids") + StringPool.DOT + booking_id);
                stat.set("project_ids", stat.getStr("project_ids") + StringPool.DOT + project_id);
                stat.update();
            }
        } catch (Exception e) {
            logger.error("booking error!", e);
            return false;
        }
        return true;
    }
}
